package com.test.tiles;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

import com.test.tiles.model.vo.TestVo;
import com.test.tiles.model.vo.UserVo;
import com.test.tiles.model.vo.bbs.Bbs;
import com.test.tiles.service.LoginService;
import com.test.tiles.util.FileUpload;
import com.test.tiles.util.ParamUtil;
import com.test.tiles.util.SessionUtil;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	private LoginService loginService;
	@Autowired
	private SessionUtil sessionUtil;
	
	//메인 요청
	@RequestMapping(value = {"/test/defualt","/index" , "/"}, method = RequestMethod.GET)
	public String defualt(Locale locale, Model model, TestVo vo,UserVo user) {
		
		System.out.println("user name = " + user.getName());
		
		System.out.println("session user = " + sessionUtil.getUser().getName());
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		TestVo productList = null;
		try{
			productList = loginService.selectProduct(vo);
		}catch(Exception e){
			e.printStackTrace();
		}
		model.addAttribute("productList", productList );
		
		return "test/defualt";
	}
	
	//상품리스트 요청
	@RequestMapping(value = "/test/category", method = RequestMethod.GET)
	public String category(Model model, TestVo vo) {
		TestVo productList = null;
		System.out.println("user_id = " + sessionUtil.getUser().getUser_id());
		try{
			productList = loginService.selectProduct(vo);
		}catch(Exception e){
			e.printStackTrace();
		}
		model.addAttribute("productList", productList );
		return "test/category";
	}
	
	//상품 상세 요청
	@RequestMapping(value = "/test/prdtdetail", method = RequestMethod.GET)
	public String prdtdetail(Locale locale, Model model, TestVo vo) {
		logger.info("Welcome home! The client locale is {}.", locale);
		TestVo productInfo = null;
		try{
			productInfo = loginService.selectInfom(vo);
		}catch(Exception e){
			e.printStackTrace();
		}
		model.addAttribute("productInfo", productInfo );
		
		return "test/prdtdetail";
	}
	
	//로긴 회원 가입
	//상품 상세 요청
	@RequestMapping(value = "/terms", method = RequestMethod.GET)
	public String terms(Locale locale, Model model, TestVo vo) {
		return "terms";
	}
	
	@RequestMapping(value = "/userInfoForm", method = RequestMethod.GET)
	public String userInfoForm(Locale locale, Model model, TestVo vo) {
		return "userInfoForm";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Locale locale, Model model, TestVo vo) {
		return "login";
	}
	
	@RequestMapping(value = "/board/list", method = RequestMethod.GET)
	public String list(Locale locale, Model model, Bbs vo) {
		List<Bbs> bbsList = loginService.selectBBS(vo);
		model.addAttribute("code", vo.getCode());
		model.addAttribute("bbsList", bbsList);
		return "board/list";
	}
	
	@RequestMapping(value = "/board/edit")
	public String edit(Locale locale, Model model, Bbs vo, HttpServletRequest request) {
		int no = vo.getNo();
		if(no !=0){
			Bbs bbsInform = loginService.selectBbsInform(vo);
			model.addAttribute("bbsInform", bbsInform);
			model.addAttribute("code", bbsInform.getCode());
		}else{
			model.addAttribute("code", vo.getCode());
		}
		return "board/edit";
	}
	
	@RequestMapping(value = "/board/save")
	public String save(Locale locale, Model model, Bbs vo , HttpServletRequest request) {
		System.out.println("vo" + vo.getContents());
		int no = loginService.insertBBS(vo);
		System.out.println("no " + no);
		return "redirect:/board/inform.htm?no="+no;
	}
	
	@RequestMapping(value = "/board/inform")
	public String inform(Locale locale, Model model, Bbs vo , HttpServletRequest request) {
		Bbs bbsInform = loginService.selectBbsInform(vo);
		model.addAttribute("bbs", bbsInform);
		return "board/inform";
	}
	
	@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
	 public String fileUpload(Model model, MultipartRequest multipartRequest) throws IOException{
		MultipartFile file = multipartRequest.getFile("upload");   //뷰에서 form으로 넘어올 때 name에 적어준 이름입니다.
		Calendar cal = Calendar.getInstance();
		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		String replaceName = cal.getTimeInMillis() +fileName+ fileType;  //파일 이름의 중복을 막기 위해서 이름을 재설정합니다.
		
		String path = "C:/images";	//제 바탕화면의 upload 폴더라는 경로입니다. 자신의 경로를 쓰세요.
		FileUpload.fileUpload(file, path, replaceName);
		String result = "&bNewLine=true";
		result += "&sFileName="+replaceName;
		result += "&sFileURL=/images/"+replaceName;
		return "redirect:/resources/smarteditor/photo_uploader/popup/callback.html?"+result;
	 }
	
	
	@RequestMapping(value = "/fileUploadHtml5", method = RequestMethod.POST)
	 public @ResponseBody String fileUploadHtml5(Model model, HttpServletRequest request) throws IOException{
		String path = "C:/images";	//제 바탕화면의 upload 폴더라는 경로입니다. 자신의 경로를 쓰세요.
		//String path = "/home/hosting_users/tkgodtjd/images";	//제 바탕화면의 upload 폴더라는 경로입니다. 자신의 경로를 쓰세요.
		System.out.println("getCharacterEncoding = " + request.getCharacterEncoding());
		String contentType =request.getHeader("contentType");
		String fileSize = request.getHeader("file-size");
		String fileType = request.getHeader("file-Type");
		String fileName = request.getHeader("file-name"); 
		//URLDecoder.decode(request.getHeader("file-name"), "UTF-8");
		
		fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		System.out.println(contentType);
		System.out.println(fileName);
		System.out.println(fileSize);
		System.out.println(fileType);
		InputStream is = request.getInputStream();
		Calendar cal = Calendar.getInstance();
		String replaceName = cal.getTimeInMillis()+fileName;  //파일 이름의 중복을 막기 위해서 이름을 재설정합니다.
		String result = "&bNewLine=true";
		result += "&sFileName="+replaceName;
		//result += "&sFileURL=/images/"+replaceName;
		result += "&sFileURL=/images/"+replaceName;
		//result = URLDecoder.decode(result, "UTF-8");
		System.out.println("result" + result);
		FileUpload.fileUpload(is, path, replaceName);
		return result;
	 }
	
	//로그인
	
	@RequestMapping(value = "/loginProccess", method = RequestMethod.POST)
	public String loginProccess(Locale locale, Model model, UserVo vo) {
		UserVo r_user = loginService.login(vo);
		if(r_user !=null){
			r_user.setLogin(true);
			sessionUtil.setUser(r_user);
			System.out.println("user_id = " +r_user.getUser_id());
		}
		return "redirect:/";
	}
	
}
